<template>
  <div class="row">
    <h2 v-if="firstSearch">请输入关键字进行搜索</h2>
    <h2 v-else-if="loading">Loading...</h2>
    <h2 v-else-if="errorMsg">{{errorMsg}}</h2>
    <div class="card" v-for="(user, index) in users" :key="index" v-else>
      <a :href="user.url" target="_blank">
        <img :src="user.avatar_url" style='width: 100px'/>
      </a>
      <p class="card-text">{{user.username}}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      users: [], // 用户信息列表
      firstSearch: true, // 初始页面显示
      loading: false, // 搜索时显示
      errorMsg: '' // 请求错误时显示
    }
  },
  mounted() {
    // 接收事件
    this.$eventBus.$on('search', async searchName => {
      if(searchName) {
        this.firstSearch = false
        this.loading = true

        // 发送请求
        const response = await axios.get('https://api.github.com/search/users', {
          params: {
            q: searchName
          }
        })
        
        try {
          const result = response.data
          const users = result.items.map(item => ({
            username: item.login,
            url: item.html_url,
            avatar_url: item.avatar_url
          }))
          this.users = users

          this.loading = false
        } catch (error) {
          this.errorMsg = '请求出错,' + error.message
          this.loading = false
        }

      }
    })
  }
}
</script>

<style scoped>
.card {
  float: left;
  width: 33.333%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: .75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>